package com.woniuxy.book.controller;


import cn.hutool.core.bean.BeanUtil;
import com.woniuxy.book.controller.form.orderinfo.OrderForm;
import com.woniuxy.book.controller.form.orderinfo.PagePayForm;
import com.woniuxy.book.entity.OrderInfo;
import com.woniuxy.book.entity.PageInfo;
import com.woniuxy.book.param.orderinfo.OrderParam;
import com.woniuxy.book.param.orderinfo.PagePayParam;
import com.woniuxy.book.service.OrderInfoService;
import com.woniuxy.book.service.dto.OrderInfoDTO;
import com.woniuxy.book.util.JWTUtil;
import com.woniuxy.book.util.RedisUtil;
import com.woniuxy.book.util.Result;
import io.jsonwebtoken.Claims;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author li
 * @since 2024年2月09日
 */
@RestController
@RequestMapping("/orderInfo")
public class OrderInfoController {

    @Resource
    private RedisUtil redisUtil;
    @Resource
    private OrderInfoService orderInfoService;

    @PostMapping("/user/order")
    public Result order(@RequestBody OrderForm form, @RequestHeader("token") String token) throws Exception {
        String refreshToken = redisUtil.get(token);
        Integer userId = (Integer) JWTUtil.getSubject(refreshToken);
        OrderParam param = BeanUtil.toBean(form, OrderParam.class);
        param.setUserId(userId);
        OrderInfoDTO dto = orderInfoService.order(param);
        return Result.success("下单成功", dto);
    }

    @PostMapping("/user/pagePay")
    public Result pagePay(@RequestBody PagePayForm form, @RequestHeader("token") String token) throws Exception {
        String refreshToken = redisUtil.get(token);
        Integer userId = (Integer) JWTUtil.getSubject(refreshToken);
        PagePayParam param = BeanUtil.toBean(form, PagePayParam.class);
        param.setUserId(userId);
        String page = orderInfoService.pagePay(param);
//        response.setContentType("text/html;charset=utf-8");
        return Result.success("页面响应成功", page);
    }

    @GetMapping({"/user/selectOrders","/admin/selectOrders"})
    public Result selectOrders(Integer pageNum, Integer pageSize, Integer orderState, @RequestHeader("token") String token) {
        String refreshToken = redisUtil.get(token);
        Integer userId = (Integer) JWTUtil.getSubject(refreshToken);
        Claims claims = JWTUtil.parseToken(refreshToken);
        String role = (String) claims.get("role");
        PageInfo pageInfo = orderInfoService.selectOrders(pageNum, pageSize, orderState, userId,role);
        return Result.success("查询订单列表成功", pageInfo);
    }

    @PostMapping("/notify")
    public String notifyHandlerOrder(HttpServletRequest request) throws Exception {
        //异步回调主要代码
        //获取支付宝POST过来的反馈信息
        //在控制层从request取出支付宝传过来的参数
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        orderInfoService.handlerOrder(params);
        return "SUCCESS";
    }


    @GetMapping("/user/deleteOrder")
    public Result deleteOrder(String orderNum,@RequestHeader("token") String token){
        String refreshToken = redisUtil.get(token);
        Integer userId = (Integer) JWTUtil.getSubject(refreshToken);
        orderInfoService.deleteOrder(orderNum,userId);
        return Result.success("删除订单成功",null);
    }

    @GetMapping("/user/findSingleOrder")
    public Result findSingleOrder(String orderNum,@RequestHeader("token") String token){
        String refreshToken = redisUtil.get(token);
        Integer userId = (Integer) JWTUtil.getSubject(refreshToken);
        OrderInfo orderInfo = orderInfoService.findSingleOrder(orderNum,userId);
        return Result.success("查询订单信息成功",orderInfo);
    }


}

